package com.example.cardserver.controller;

import com.example.cardserver.entity.Goods;
import com.example.cardserver.service.IGoodsService;
import com.example.cardserver.service.IOrderService;
import com.example.cardserver.service.ex.GoodsException;
import com.example.cardserver.util.JsonResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RequestMapping("market")
@RestController
public class GoodsController extends BaseController{
    @Resource
    private IGoodsService goodsService;
    
    @RequestMapping("list")
    public JsonResult<List<Goods>> getList(){
        List<Goods> data = goodsService.findList();
        return new JsonResult<List<Goods>>(OK, data);
    }
    
    
    
    @RequestMapping("good")
    public JsonResult<Goods> getSingleGoods(){
        return new JsonResult<Goods>(OK);
    }

    public static final int AVATAR_MAX_SIZE = 10 *1024 * 1024;
    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }
    
    @RequestMapping("changepicture")
    public JsonResult<String> changePic(HttpSession session, @RequestParam MultipartFile file){
        if(file.isEmpty()){
            throw new GoodsException("未选择文件");
        }
        if(file.getSize() > AVATAR_MAX_SIZE){
            throw new GoodsException("文件大小超出限制");
        }
        String type = file.getContentType();
        if(!AVATAR_TYPE.contains(type)){
            throw new GoodsException("文件类型不支持");
        }
        
        String parent = session.getServletContext().getRealPath("upload");
        File dir = new File(parent);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String originalFileName = file.getOriginalFilename();
        System.out.println("OriginalFileName"+originalFileName);
        int index = originalFileName.lastIndexOf(".");
        String suffix = originalFileName.substring(index);
        String filename= UUID.randomUUID().toString().toUpperCase() + suffix;
        File dist = new File(dir, filename);
        try{
            file.transferTo(dist);
        }catch (Exception e){
            throw new GoodsException("文件异常");
        }
        Integer id = getIdFromSession(session);
        String picture = "upload"+filename;
        goodsService.changePicture(id, picture);
        return new JsonResult<>(OK, picture);
    } 
}
